package com.droidwatcher.util;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Created by Administrator on 2018/3/1.
 */

public class Utils {
    public static boolean isEmailFormat(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);

        return m.matches();
    }

    public static OkHttpClient getOkHttpClient() {

        AXLog.e("wzytest","进入拦截器");
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient
                .Builder();
        //OkHttp进行添加拦截器loggingInterceptor
        httpClientBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {

                Request request = chain.request();
                RequestBody requestBody= request.body();
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);
                Charset charset = null;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset();
                }
                if(charset==null){
                    charset = Charset.forName("UTF-8");
                }
                String paramsStr = buffer.readString(charset);

                AXLog.e("wzytest","request.boy:"+request.url()+" body:"+paramsStr);

                Response response = chain.proceed(request);

                return response;
            }
        });
        return httpClientBuilder.build();
    }
}
